package cn.bellychang.leetcode.question155;

/**
 * @author ChangLiang
 * @date 2021/1/27
 */
public class MinStack {

    private int[] items;

    private int count;

    private int capacity;

    private static final int EXTEND_FACTOR = 2;

    /** initialize your data structure here. */
    public MinStack() {
        this.capacity = 2;
        this.items = new int[capacity];
        this.count = 0;
    }

    public void push(int x) {
        if (count == capacity) {
            int[] dest = new int[capacity * EXTEND_FACTOR];
            System.arraycopy(items,0, dest, 0, count);
            items = dest;
            capacity = capacity * EXTEND_FACTOR;
        }
        items[count] = x;
        count++;
    }

    public void pop() {
        if (count == 0) {
            throw new RuntimeException("stack is empty");
        }
        count--;
    }

    public int top() {
        if (count == 0) {
            throw new RuntimeException("stack is empty");
        }
        return items[count - 1];
    }

    public int getMin() {
        if (count == 0) {
            throw new RuntimeException("stack is empty");
        }
        int minValue = items[0];
        for (int i = 1; i < count; i++) {
            if (minValue >= items[i]) {
                minValue = items[i];
            }
        }
        return minValue;
    }
}
